package cn.schoolwow.quickdao.module.database.dml.json.flow.insert.common;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.module.database.dml.json.flow.common.SetColumnNameListFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.util.List;

public class SetInsertJSONObjectStatementFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        flowContext.executeFlowList(new SetColumnNameListFlow());
        setStatement(flowContext);
    }

    @Override
    public String name() {
        return "设置插入JSONObject的SQL语句";
    }

    private void setStatement(FlowContext flowContext){
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        String tableName = (String) flowContext.checkData("tableName");
        List<String> columnNameList = (List<String>) flowContext.checkData("columnNameList");

        StringBuilder sqlBuilder = new StringBuilder("insert into " + quickDAOConfig.databaseContext.databaseProvider.escape(tableName) + "(");
        for(String columnName:columnNameList){
            sqlBuilder.append(quickDAOConfig.databaseContext.databaseProvider.escape(columnName) + ",");
        }
        sqlBuilder.deleteCharAt(sqlBuilder.length() - 1);
        sqlBuilder.append(") values(");
        for(String columnName:columnNameList){
            sqlBuilder.append("?,");
        }
        sqlBuilder.deleteCharAt(sqlBuilder.length() - 1);
        sqlBuilder.append(")");
        flowContext.putTemporaryData("sql", sqlBuilder.toString());
    }
}
